package com.sketch.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sketch.commom.PageResult;
import com.sketch.commom.Result;
import com.sketch.commom.enums.VipEnum;
import com.sketch.entity.WebUser;
import com.sketch.entity.dto.WebUserDTO;
import com.sketch.mapper.WebUserMapper;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class WebUserService {
    @Resource
    private WebUserMapper webUserMapper;
    public Result list(Long uid, Integer vip, Integer status, Integer page, Integer size) {
        LambdaQueryWrapper<WebUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(uid),WebUser::getUserId, uid)
                .eq(!ObjectUtils.isEmpty(status),WebUser::getStatus, status);

        if (VipEnum.VIP.equals(vip)) {
            LocalDateTime currentTime = LocalDateTime.now();
            queryWrapper.and(wrapper -> wrapper
                    .ge(WebUser::getVipEndTime, currentTime)
                    .or().isNull(WebUser::getVipEndTime)
            );
        } else if (VipEnum.NOT_VIP.equals(vip)) {
            LocalDateTime currentTime = LocalDateTime.now();
            queryWrapper.and(wrapper -> wrapper
                    .gt(WebUser::getVipEndTime, currentTime)
            );
        }
        Page<WebUser> userPage = new Page<>(page, size);
        IPage<WebUser> result = webUserMapper.selectPage(userPage, queryWrapper);
        PageResult dtoPage = new PageResult<>();
        BeanUtils.copyProperties(result,dtoPage);
        List<WebUserDTO> list = new ArrayList<>();
        if(ObjectUtils.isEmpty(result.getRecords())){
            return Result.success(dtoPage);
        }
        result.getRecords().forEach(e->{
            WebUserDTO webUserDTO = new WebUserDTO();
            BeanUtils.copyProperties(e,webUserDTO);
            list.add(webUserDTO);
        });
        dtoPage.setList(list);
        return Result.success(dtoPage);
    }

}
